package service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.junit.Test;

import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by fanzhenyu02 on 2019/11/14.
 */
public class SecNetStatistics {


    /**
     * 向指定URL发送GET方式的请求
     */
    public static Object sendGet(String alarmQueryUrl) throws Exception {
        if (StringUtils.isBlank(alarmQueryUrl)) {
            return null;
        }

        StringBuilder result = new StringBuilder();
        try {
            URL realUrl = new URL(alarmQueryUrl);
            //打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            //设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.addRequestProperty("Cookie", "_lxsdk=161fb1d83dec8-03ab48f553411f-16386656-13c680-161fb1d83dec8; _ga=GA1.2.806956889.1520336520; _lxsdk_cuid=161fef2dd92c8-062f63fabc9de6-16386656-13c680-161fef2dd92c8; gr_user_id=09d38b6a-3543-4c46-a5ed-9bcfa4dfb3cb; _jzqa=1.3919124163620041000.1522289486.1522289486.1522289486.1; __mta=42178074.1522049991234.1526875746425.1526875766341.61; skmtutc=y4d2j2Y8+enMdDko7qIwH9sHnwU91UY1SqzBYsZW3friNNshghDs0y4pcx1AsbRI-tlvYlKKYKZmLSLzNSkECBI7pVeQ=; ssoid=eAHjYBR4NqOdUWH5k01L3-gacaUkmxsbJZkbGFlYKSSlmqYZGBiZJVqmppikmpklJhmkapmYGiQZGxsapCUaOlkqPG3pfvFeV4PRiKBiC5A1Dmwel78sW_5aN0ohLcU8NTnNKDnFQCvZJMnQJMnc2MAoycLUwjQp0cLEOAkAud8wkQ**eAENx9sBADEEBMCWPCIoh7D9l3A3fyNrOUY4MovSu7pk9Rf1ZJhbrifCAT63hqAS6TSdr6gRH1GmEkY; mispic=fanzhenyu02; user=%E5%87%A1%E6%8C%AF%E5%AE%87; _lxsdk_s=16eb4e8c0db-e3f-ea1-aac%7Cfanzhenyu02%7C91");//设置获取的cookie

            //建立实际的连接
            conn.connect();
            // 定义 BufferedReader输入流来读取URL的响应
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception e) {
            System.err.println("发送GET请求出现异常!");
        }

        JSONObject resultJson = JSONObject.parseObject(result.toString());
        if (null == resultJson.get("data")) {
            throw new Exception("获取数据异常");
        }

        return resultJson.get("data");
    }


    // HTTP POST请求
    private static void sendPost(String url) throws Exception {
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        //添加请求头
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
        con.addRequestProperty("Cookie", "_lxsdk=161fb1d83dec8-03ab48f553411f-16386656-13c680-161fb1d83dec8; _ga=GA1.2.806956889.1520336520; _lxsdk_cuid=161fef2dd92c8-062f63fabc9de6-16386656-13c680-161fef2dd92c8; gr_user_id=09d38b6a-3543-4c46-a5ed-9bcfa4dfb3cb; _jzqa=1.3919124163620041000.1522289486.1522289486.1522289486.1; __mta=42178074.1522049991234.1526875746425.1526875766341.61; skmtutc=y4d2j2Y8+enMdDko7qIwH9sHnwU91UY1SqzBYsZW3friNNshghDs0y4pcx1AsbRI-tlvYlKKYKZmLSLzNSkECBI7pVeQ=; u=1377140507; user=%E5%87%A1%E6%8C%AF%E5%AE%87; SAVED_URL=http%3A%2F%2Fview.funds.sankuai.com%2F; ssoid=eAHjYBR4NqOdUeFI2_XTz3WNuFKSzY2NkswNjCysFJJSTdMMDIzMEi1TU0xSzcwSkwxStUxMDZKMjQ0N0hINnSwV7s581_1aV4PRiKBiC5A1DmweZzu7Tj_TjVIwS7FISUxLMTJI1EoxMUw1SbQwNUyyNDM1TLRMsTBNMwIAq6swEg**eAEFwYEBwCAIA7CXwMLEc1qU_09YYtEgYe65qncDcU8RKSu6eL_W4jxOD_RCOG-l5LA96fEDQWcSGQ; mispic=fanzhenyu02");//设置获取的cookie

//        String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";

        //发送Post请求
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
//        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
//        System.out.println("Post parameters : " + urlParameters);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        //打印结果
        System.out.println(response.toString());

    }

    @Test
    public static Set<String> getServiceGroup() {
        Set<String> serviceAppKeyList = new HashSet<String>();
        List<String> groupMember = Arrays.asList("zhangyujing", "chengjunbao", "zhengxiaoming", "tangxinqi", "shangxiaofei", "xuronghua", "wangbiao03", "zhaodaojun", "zhaoweilong02", "lihaibo04", "fanzhenyu02");

        for (String leader : groupMember) {
            String requestAppKeyUrl = "http://octo.sankuai.com/api/apps?username=" + leader;
            JSONArray result = null;
            try {
                result = (JSONArray) sendGet(requestAppKeyUrl);
            } catch (Exception e) {
                System.out.println("网络请求失败");
            }

            if (null == result) {
                continue;
            }

            for (Object serviceAppKey : result) {
                serviceAppKeyList.add((String) serviceAppKey);
            }
        }

        return serviceAppKeyList;
    }

    public static void doCount() {
//        Set<String> services = getServiceGroup();
        Set<String> services = new HashSet<String>();
        services.add("com.sankuai.pay.bankgw.enterpay");
        for (String ser : services) {
            System.out.println("当前服务(appkey: " + ser + ") 外网访问详情 ");
            String requestAppKeyUrl = "https://netsec.sankuai.com/api/fw/nat/static?s=" + ser;
            JSONArray result = null;
            try {
                result = (JSONArray) sendGet(requestAppKeyUrl);
            } catch (Exception e) {
                System.out.println("网络请求失败");
                System.out.println("\n--------------------------------------------------------");
            }

            if (null == result) {
                continue;
            }


            for (Object oneAccess : result) {
                JSONObject accessRecord = (JSONObject) oneAccess;
                System.out.println("美团服务主机：" + accessRecord.get("源地址") + "，外网目标地址：" + getProcessedIpList((String) accessRecord.get("目标地址集")) + "：" + accessRecord.get("目标端口集合") + " ，近7天共访问 " + accessRecord.get("访问量(次数)") + " 次");
            }

            System.out.println("\n--------------------------------------------------------");

        }
    }

    public static String getProcessedIpList(String ipInput) {
        if (ipInput.length() <= 16) {
            return ipInput;
        } else {
            return ipInput.replaceAll(",", "|");
        }
    }


    public static void doErrorCount() {
        String requestUrl = "http://case.sankuai.com/api/alarm/history?tab=alarmHistory&source=falcon&source=oceanus&source=cat&source=octo&source=falconlog&source=crane&source=rhino&status=PROBLEM&priority=0&priority=2&priority=1&env=prod&from=0&size=1000000&receiver=zhangyujing";

        // 监控配置的API服务列表
        List<String> serviceList = Arrays.asList("com.sankuai.pay.fundstransfer.gw");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        JSONArray totalResult = new JSONArray();
        for (String service : serviceList) {
            requestUrl = addTime(requestUrl, "2019-11-02", "2019-11-03");
            String tempUrl = requestUrl + "&appkey=" + service;

            // 请求监控数据
            JSONArray dailyResult = null;
            try {
                sendGet(tempUrl);
//                dailyResult = (JSONArray) ( ((JSONObject)sendPost(tempUrl)).get("data"));
//                sendPost(tempUrl);
            } catch (Exception e) {
                System.out.println("查询历史监控数据失败！");
            }

            totalResult.addAll(dailyResult);

        }

        System.out.println(totalResult);
    }

    public static String addTime(String url, String begin, String end) {
        url += "&begin=" + begin + "%2000%3A00%3A00";
        url += "&end=" + end + "%2000%3A00%3A00";
        return url;
    }

    public static void main(String[] args) {


//        doErrorCount();
        try {
            final Object o = sendGet("http://bo-gating.coupang.net/gated/product/all-for/8aeabc93-a9a5-4806-bb71-42af89711c3f");
            System.out.println(o.toString());
        } catch (Exception e) {
//            log.error("transaction got error!", e);
        }

    }


//    public static void main(String[] args) {
//        SecNetStatistics ss = new SecNetStatistics();
//        ss.doErrorCount();
//
////        PrintStream out = null;
////        try {
////            out = new PrintStream("/Users/vonmax/Downloads/result.txt");
////        } catch (FileNotFoundException e) {
////            e.printStackTrace();
////        }
////        System.setOut(out);
////
////        doCount();
//
//    }


}
